package org.example.managementsystem.repository;

import org.example.managementsystem.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class UserDao {
    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public UserDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * 根据工号查询用户
     */
    public User getUserByJobNumber(String jobNumber) {
        String sql = "SELECT * FROM user WHERE job_number = ?";
        List<User> users = jdbcTemplate.query(sql, new UserRowMapper(), jobNumber);
        return users.isEmpty() ? null : users.get(0);
    }

    /**
     * 根据手机号查询用户
     */
    public User getUserByPhone(String phone) {
        String sql = "SELECT * FROM user WHERE phone = ?";
        List<User> users = jdbcTemplate.query(sql, new UserRowMapper(), phone);
        return users.isEmpty() ? null : users.get(0);
    }

    /**
     * 添加用户
     */
    public int insertUser(User user) {
        String sql = "INSERT INTO user (job_number, password, phone, role) VALUES (?, ?, ?, ?)";
        return jdbcTemplate.update(sql, 
                user.getJobNumber(), 
                user.getPassword(), 
                user.getPhone(), 
                user.getRole());
    }

    /**
     * 更新用户
     */
    public int updateUser(User user) {
        String sql = "UPDATE user SET password = ?, phone = ?, role = ? WHERE job_number = ?";
        return jdbcTemplate.update(sql, 
                user.getPassword(), 
                user.getPhone(), 
                user.getRole(), 
                user.getJobNumber());
    }

    /**
     * 删除用户
     */
    public int deleteUser(String jobNumber) {
        String sql = "DELETE FROM user WHERE job_number = ?";
        return jdbcTemplate.update(sql, jobNumber);
    }

    /**
     * 用户行映射器
     */
    private static class UserRowMapper implements RowMapper<User> {
        @Override
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User();
            user.setJobNumber(rs.getString("job_number"));
            user.setPassword(rs.getString("password"));
            user.setPhone(rs.getString("phone"));
            user.setRole(rs.getString("role"));
            return user;
        }
    }
}